<script setup lang="ts">
import { add, update, checkExist } from '@/api/system/user'
import { getRoleList } from '@/api/system/role'
import { getDeptSelect } from '@/api/system/dept'
import { useForm } from '@/hooks/useForm'
import type { FormRules } from 'element-plus'
import { isMainAccount, isMobile } from '@/utils/validate'


const emit = defineEmits(['refresh'])
const initData = { accountNonExpired: true, accountNonLocked: true, credentialsNonExpired: true }
const {
  formRef,
  pageTypes, selectLoading,
  title, visible, loading,
  formData, oldFormData,
  open,
  close,
  submitForm,
} = useForm<SysUserType>({ add, update, initData }, emit)

defineExpose({
  open
});

/**
 * 表单规则
 */
const rules = reactive<FormRules>({
  username: [{ required: true, asyncValidator: usernameValidator, message: '必填项！', trigger: 'blur' }],
  nickName: [{ required: true, message: '必填项！', trigger: 'blur' }],
  mobile: [{ required: true, asyncValidator: mobileValidator, message: '必填项！', trigger: 'blur' }],
  roleIds: [{ required: true, message: '必填项！', trigger: 'blur' }],
  deptIds: [{ required: true, message: '必填项！', trigger: 'blur' }],
  email: [{ required: true, message: '必填项！', trigger: 'blur' }],
  accountNonExpired: [{ required: true, message: '必填项！', trigger: 'blur' }],
  accountNonLocked: [{ required: true, message: '必填项！', trigger: 'blur' }],
  credentialsNonExpired: [{ required: true, message: '必填项！', trigger: 'blur' }],
})

// 修改时禁用
// const disabled = computed(() => type.value === 'edit')

// 监听打开窗口时，进行逻辑处理
watch(() => visible.value, (val) => {
  if (!val) return
  loadRoleOptions()
  loaddeptOptions()
});

// 查询所有角色用于下拉框
const roleOptions = ref([])
async function loadRoleOptions() {
  try {
    selectLoading.value = true
    const { page, size } = pageTypes.value
    const { data } = await getRoleList({ page, size })
    console.log('查询所有角色用于下拉框', data);

    if (data.results && data.results.length > 0) {
      // 转换为下拉框的目标类型数据
      roleOptions.value = data.results.map((item: any) => ({ value: item.id, label: item.roleName }));
    } else {
      roleOptions.value = [];
    }
  } catch (error) {
  } finally {
    selectLoading.value = false;
  }
}

// 查询部门树用于下拉框
const deptOptions = ref([])
async function loaddeptOptions() {
  try {
    selectLoading.value = true;
    const { page, size } = pageTypes.value
    const { data } = await getDeptSelect({ page, size })
    console.log('查询部门树用于下拉框', data);

    if (data.results && data.results.length > 0) {
      // 转换为下拉框的目标类型数据
      deptOptions.value = data.results
    } else {
      deptOptions.value = [];
    }
  } catch (error) {
  } finally {
    selectLoading.value = false;
  }
}

//校验用户帐号是否存在
async function usernameValidator(_rule: any, value: string, callback: Function) {
  if (!value || value == '') {
    return callback(new Error('用户帐号为必填项！'));
  }
  if (!isMainAccount(value)) {
    return callback(new Error('用户帐号必须为6~30位数字/字母/下划线！'));
  }
  if (oldFormData.value.username !== value) {
    const { data } = await checkExist({ username: value });
    // data true存在：不通过，false不存在：则通过
    if (data) return callback(new Error('用户帐号已被注册，请更新一个'));
  }
  // 通过放行
  callback();
}

// 校验手机号
async function mobileValidator(_rule: any, value: string, callback: Function) {
  // 可以为空，直接放行
  if (!value || value == '') {
    return callback();
  }
  // 校验手机号是否有效格式
  if (!isMobile(value)) {
    return callback(new Error('手机号码格式不正确！'));
  }
  // 请求判断是否唯一性
  if (oldFormData.value.mobile !== value) {
    const { data } = await checkExist({ mobile: value });
    if (data) return callback(new Error('手机号码已存在，请更换一个！'));
  }
  // 通过放行
  callback();
}
</script>

<template>
  <el-dialog :title="`${title}用户`" v-model="visible" draggable :before-close="close" :close-on-click-modal="false"
    destroy-on-close>
    <el-scrollbar max-height="460px">
      <el-form v-loading="selectLoading" ref="formRef" :model="formData" :rules="rules" label-width="100">
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户账号" prop="username">
              <el-input v-model.trim="formData.username" placeholder="请输入用户账号" maxlength="30" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户昵称" prop="nickName">
              <el-input v-model="formData.nickName" placeholder="请输入用户昵称" maxlength="30" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="mobile">
              <el-input v-model.trim="formData.mobile" placeholder="请输入手机号码" maxlength="20" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电子邮箱" prop="email">
              <el-input v-model.trim="formData.email" placeholder="请输入电子邮箱" maxlength="30" show-word-limit clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分配角色" prop="roleIds">
              <el-select-v2 v-model="formData.roleIds" multiple :options="roleOptions" placeholder="请选择分配给用户的角色"
                style="width: 100%" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分配部门" prop="deptIds">
              <el-tree-select v-model="formData.deptIds" multiple show-checkbox :data="deptOptions" filterable
                placeholder="请选择分配给用户的部门" style="width: 100%" clearable :render-after-expand="false" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="帐号锁定" prop="accountNonLocked">
              <el-radio-group v-model="formData.accountNonLocked">
                <el-radio :value="true">未锁定</el-radio>
                <el-radio :value="false">已锁定</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="帐号过期" prop="accountNonExpired">
              <el-radio-group v-model="formData.accountNonExpired">
                <el-radio :value="true">未过期</el-radio>
                <el-radio :value="false">已过期</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remarks">
              <el-input v-model="formData.remarks" type="textarea" :autosize="{ minRows: 5 }" placeholder="请输入备注信息"
                maxlength="500" clearable show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-scrollbar>
    <template #footer>
      <div class="flex items-center justify-center">
        <el-button class="w-29" type="info" @click="close">取 消</el-button>
        <el-button class="w-29" type="primary" :loading="loading" @click="submitForm">
          {{ loading ? '正在提交 ...' : '提 交' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped></style>